package cn.taketoday.live.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.taketoday.live.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author BanqiJane
 */
@Slf4j
public class ProFileTools {

  public static Map<String, String> read(String filename) {
    String path = FileUtils.getApplicationPath();
    File file = new File(path);
    file.setWritable(true, false);
    if (!file.exists())
      file.mkdirs();
    file = new File(path + "/" + filename);
    file.setWritable(true, false);
    if (file.exists() == false)
      try {
        file.createNewFile();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    ConcurrentHashMap<String, String> hashtables = new ConcurrentHashMap<>();
    String dataString = null;
    String[] strings = null;
    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
      while ((dataString = bufferedReader.readLine()) != null) {
        strings = dataString.split(":@:");
        if (strings.length == 2) {
          hashtables.put(strings[0], strings[1]);
        }
        else {
          return null;
        }
      }
    }
    catch (IOException e) {
      log.error("文件 ：{} 读取失败", file, e);
    }
    return hashtables;

  }

  public static void write(Hashtable<String, String> hashtables, String filename) {
    String path = FileUtils.getApplicationPath();
    File file = new File(path);
    file.setWritable(true, false);
    if (file.exists() == false)
      file.mkdirs();
    file = new File(path + "/" + filename);
    file.setWritable(true, false);
    final StringBuffer stringBuffer = new StringBuffer();
    try {
      file.createNewFile();
    }
    catch (IOException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    }
    BufferedWriter bufferedWriter = null;
    try {
      bufferedWriter = new BufferedWriter(new FileWriter(file));
      hashtables.forEach((k, v) -> {

        stringBuffer.append(k);
        stringBuffer.append(":@:");
        stringBuffer.append(v);
        stringBuffer.append("\r\n");
      });
      bufferedWriter.write(stringBuffer.toString());
      bufferedWriter.flush();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      if (bufferedWriter != null) {
        try {
          bufferedWriter.close();
        }
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
